<template>
	<view class="container">
		<view class="line"></view>
		<view class="inner">
			<view class="name">{{ vdata.couponInfo.couponName }}</view>
			<!-- <view class="desc">满100.01元立减100元</view> -->
			<!-- <view class="over-time">有效期至{{ dayjs(vdata.couponInfo.eTime).format('YYYY-MM-DD') }}</view> -->
			<view  class="verified_score">消耗福分：{{vdata.scoreNeed}}</view>
			<view class="desc over-time">有效期至{{ vdata.couponInfo.eTime }}</view>
			<view class="image">
				<!-- <image src="@/static/new/user/big-coupon-bg.png" style="width: 402rpx; height: 158rpx;" /> -->
				<view class="price">
					<text>￥</text>
					<text>{{ vdata.couponInfo.couponPrice ? vdata.couponInfo.couponPrice / 100 : 0 }}</text>
				</view>
				<!-- {{vdata.couponInfo}} -->
				<view class="payAmount">
					满{{vdata.couponInfo.payAmount / 100}}元使用
				</view>
				<view class="type">
					<text v-if="vdata.couponInfo.couponType === 1">支付宝满减券</text>
					<text v-else-if="vdata.couponInfo.couponType === 2">支付宝随机减券</text>
					<text v-else-if="vdata.couponInfo.couponType === 3">微信满减券</text>
					<text v-else-if="vdata.couponInfo.couponType === 4">微信随机减券</text>
					<text v-else-if="vdata.couponInfo.couponType === 5">微信代金券</text>
					<text v-else>其他</text>
				</view>
			</view>
			<view class="dotted"></view>

			<view class="rule-wrap">
				<view>使用规则</view>
				<text>{{ vdata.couponInfo.couponRemark?.replace(/\\n/g, "\n") }}</text>
				<!-- <view v-for="item in vdata.couponInfo.couponRemark">{{ item }}</view> -->
			</view>
		</view>
		<!-- 点击导航适用门店 -->
		<!-- v-if="vdata.couponInfo.state === 0" -->
		<!-- @click="toUrl(`/pageUser/myCoupon/mchList?couponId=${vdata.couponInfo.couponId}`)" -->
		<view  class="btn-wrap">
			<view  class="btn" @click="exchange" v-if="vdata.detailType !='0'">立即兑换</view>
		</view>
<!-- 		<view v-else-if="vdata.couponInfo.state === 3" class="btn-wrap">
			<template v-if="vdata.couponInfo.isNeedActivate === 1 && vdata.couponInfo.activateType?.includes(1) && vdata.couponInfo.activateType?.includes(2)">
				<template v-if="vdata.isAuth == 1">
					<view class="btn" style="background: #FF8833;" @click="onOpenQr">出示激活码</view>
					<view @click="toUrl(`/pageUser/realName/index`)" class="btn">去认证</view>
				</template>
				<template v-else-if="vdata.isAuth == 0">
					<view class="btn" style="background: #ccc;color: #fff;">激活中，状态稍后刷新</view>
				</template>
			</template>
			<template v-else-if="vdata.couponInfo.isNeedActivate === 1 && vdata.couponInfo.activateType?.includes(2)">
				<view class="btn" style="background: #FF8833;" @click="onOpenQr">出示激活码</view>
				<view class="btn" @click="toUrl(`/pageUser/myCoupon/mchList?couponId=${vdata.couponInfo.couponId}&activate=${true}`)">导航去网点</view>
			</template>
		</view> -->
		<!-- 二维码弹窗 -->
		<!-- <uni-popup ref="qrPopup" type="bottom" :is-mask-click="false">
			<view class="popup-qr">
				<text class="title">激活二维码</text>
				<uni-icons type="closeempty" size="24" color="darkgray" class="close" @click="onCloseQr()"></uni-icons>
				<view class="line"></view>
				<view class="content">
					<image mode="widthFix" :src="tool.drawQRcode(vdata.qrImage)"></image>
					
				</view>
				<text class="bottom-wrap" @click="saveQRcode()">
					保存二维码
				</text>
			</view>
		</uni-popup> -->
	</view>
</template>

<script setup>
	import tool from '@/util/tool.js'
	import dayjs from 'dayjs'
	import { $awardDetail, $realNameSendCoupon,$scoreRecordExchange } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	import { ref, reactive, onUnmounted, getCurrentInstance } from 'vue';
	import { onShow, onLoad, onHide, onUnload } from '@dcloudio/uni-app';

	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	// 二维码弹窗
	const qrPopup = ref();

	const vdata = reactive({
		isAuth: 1, // 实名状态
		couponInfo: {}, // 卡券信息
		qrImage: '', // 保存fansAwardId和商品名称
		timer: null, // 计时器
		fansAwardId: '', //
		couponId: '', //
		scoreNeed:'',//需要多少福分
		detailData:{},//传递过来的数据
		detailType:''
	})
	
	// 立即兑换
	const exchange = () =>{
		$scoreRecordExchange({
			scoreExchangeId:vdata.detailData.scoreExchangeId,
			infoType:vdata.detailData.awardType,
			name:vdata.couponInfo.couponName
		}).then(res=>{
				console.log(res,'卡券兑换')
				if(res.code ==0){
					uni.showToast({
						title: '兑换成功',
						icon: 'none',
						duration: 1000
					}) 
				}
		})
	}
	
	// 用户id
	const fansId = storageManage.fansId()
	const userId = storageManage.userId()
	onLoad(async ({detailData, couponId,scoreNeed,detailType }) => {
		vdata.detailType = detailType
		vdata.detailData = JSON.parse(decodeURIComponent(detailData))
		vdata.scoreNeed = scoreNeed
		console.log(couponId,'卡券id')
		if (vdata.isAuth != storageManage.userInfo().isAuth) {
			vdata.isAuth = storageManage.userInfo().isAuth
		}
		// vdata.fansAwardId = fansAwardId
		vdata.couponId = couponId
		// 请求卡券详情
		await getCouponDetail(couponId)
		// 实名激活 刷新卡券状态
		if (vdata.couponInfo.state === 3 && vdata.couponInfo.activateType?.includes(1) && vdata.isAuth == 0) {
			let flag = false
			vdata.timer = setInterval(() => {
				if (flag) return
				flag = true
				$awardDetail({ couponId: vdata.couponId }).then(({ bizData }) => {
					if (bizData.state == 0) {
						Object.assign(vdata.couponInfo, bizData)
						$infoBox.successToast('激活成功')
						clearInterval(vdata.timer)
					} else {
						flag = false
					}
				}).catch(() => {
					clearInterval(vdata.timer)
				})
			}, 2000)
		}
	});
	onShow(() => {
		if (vdata.isAuth != storageManage.userInfo().isAuth) {
			vdata.isAuth = storageManage.userInfo().isAuth
		}
	})
	onHide(() => {
		if (vdata.timer) {
			clearInterval(vdata.timer)
		}
	})
	onUnload(() => {
		if (vdata.timer) {
			clearInterval(vdata.timer)
		}
	})
	/**
	 * 实名认证 激活卡券
	 */
	function realNameSendCoupon() {
		const { fansAwardId, couponId } = vdata.couponInfo
		uni.showLoading({
			title: '激活中...'
		})
		$realNameSendCoupon({
			fansAwardId,
			couponId
		}).then(res => {
			// 激活成功后刷新卡券详情
			getCouponDetail( couponId).then(() => {
				uni.hideLoading(); // 隐藏 loading
				$infoBox.successToast('卡券激活成功')
			})
		})
	}
	/**
	 * 请求卡券详情
	 */
	async function getCouponDetail( couponId) {
		try {
			const { bizData } = await $awardDetail({couponId });
			Object.assign(vdata.couponInfo, bizData)
			console.log(vdata.couponInfo,'卡券详情')
			// console.log(bizData,'二维码信息')
			// if(bizData.isOpenReceipt ==0){
			// 	vdata.qrImage = JSON.stringify({
			// 		type: 'coupon',
			// 		fansAwardId,
			// 		couponName: bizData.couponName,
			// 		fansId,
			// 		couponId
			// 	});
			// }else{
			vdata.qrImage = JSON.stringify({
				type: 'coupon',
				fansAwardId,
				couponName: bizData.couponName,
				fansId,
				couponId
			});
			// }

		} catch (error) {
			// console.error("Failed to fetch coupon details:", error);
		}
	}
	/**
	 * 路由跳转
	 */
	function toUrl(url) {
		uni.navigateTo({
			url
		})
	}
	/**
	 * 展示激活二维码
	 */
	function onOpenQr() {
		qrPopup.value.open();
		let flag = false
		vdata.timer = setInterval(() => {
			if (flag) return
			flag = true
			$awardDetail({couponId: vdata.couponId }).then(({ bizData }) => {
				if (bizData.state == 0) {
					Object.assign(vdata.couponInfo, bizData)
					$infoBox.successToast('激活成功')
					onCloseQr()
				} else {
					flag = false
				}
			}).catch(() => {
				clearInterval(vdata.timer)
			})
		}, 1500)
	}
	/**
	 * 关闭二维码弹窗
	 */
	const onCloseQr = () => {
		qrPopup.value.close();
		clearInterval(vdata.timer)
	}

	function saveQRcode() {
		saveBaseImgFile(tool.drawQRcode(vdata.qrImage))
	}
	// 将base64 图片保存到本地系统相册
	function saveBaseImgFile(imgSrc) {
		uni.showLoading({
			title: '保存中...'
		})
		var writeContent = imgSrc.replace('data:image/gif;base64,', '')
		var fs = uni.getFileSystemManager();
		var number = Math.random();
		fs.writeFile({
			filePath: uni.env.USER_DATA_PATH + '/pic' + number + '.png',
			data: writeContent,
			encoding: 'base64',
			success: res => {
				uni.saveImageToPhotosAlbum({
					filePath: uni.env.USER_DATA_PATH + '/pic' + number + '.png',
					success: function(res) {
						uni.hideLoading()
						$infoBox.toast('保存成功')
					},
					fail: function(err) {
						// console.log(err)
					}
				})
				// console.log(res)
			},
			fail: err => {
				// console.log(err)
			}
		})
	}
</script>
<style lang="less">
	.container {
		width: 100%;
		min-height: 100vh;
		background: #24C789;
		overflow: hidden;
		position: relative;
		padding: 0 40rpx;
		box-sizing: border-box;

		.nav {
			width: 100%;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 999;
			background: #24C789;
		}

		.line {
			height: 20rpx;
			background: #509D67;
			border-radius: 10rpx;
			margin-top: 40rpx;
			position: relative;
		}

		.inner {
			background: #fff;
			position: relative;
			top: -10rpx;
			padding: 60rpx 0;
			margin: 0 20rpx;
			text-align: center;

			.name {
				font-weight: bold;
				font-size: 48rpx;
				color: #333333;
				padding: 0 100rpx;
			}

			.verified_score {
				margin: 24rpx 0;
				color: #d49d4e;
				font-size: 28rpx;
			}

			.desc {
				font-weight: 400;
				font-size: 28rpx;
				color: #24C789;
				margin: 20rpx 0 12rpx;
			}

			.over-time {
				font-weight: 400;
				font-size: 28rpx;
				color: #A0A9C0;
			}

			.image {
				width: 402rpx;
				height: 208rpx;
				margin: 44rpx auto 68rpx;
				background-image: url('@/static/new/user/big-coupon-bg.png');
				background-size: 402rpx 158rpx;
				background-position: 0 0;
				background-repeat: no-repeat;
				position: relative;
				display: flex;
				flex-direction: column;

				.payAmount {
					position: absolute;
					left: 36%;
					top: 120rpx;
					font-size: 24rpx;
					z-index: 10;
					color: white;
				}

				.price {

					text {
						font-weight: bold;
						color: #FFFFFF;
						line-height: 158rpx;

						&:nth-child(1) {
							font-size: 32rpx;
						}

						&:nth-child(2) {
							font-size: 80rpx;
						}
					}
				}

				.type {
					width: 402rpx;
					height: 50rpx;
					background: #F9D996;
					position: absolute;
					bottom: 0;
					font-weight: 400;
					font-size: 24rpx;
					color: #B17622;
					line-height: 50rpx;
				}
			}

			.dotted {
				border-top: 9rpx dotted #24C789;
				position: relative;

				&::before,
				&::after {
					content: '';
					display: block;
					width: 40rpx;
					height: 40rpx;
					background: #24C789;
					position: absolute;
					top: -25rpx;
					border-radius: 50%;
				}

				&::before {
					left: -20rpx;
				}

				&::after {
					right: -20rpx
				}
			}

			.rule-wrap {
				text-align: left;
				padding: 60rpx 40rpx 85rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #333333;
				display: flex;
				flex-direction: column;
				gap: 26rpx;
			}
		}


		.btn-wrap {
			width: 100%;
			padding: 24rpx 36rpx;
			box-sizing: border-box;
			background: #fff;
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			gap: 30rpx;

			.btn {
				width: 100%;
				padding: 30rpx 0;
				background: #24C789;
				border-radius: 48rpx;
				font-weight: 500;
				font-size: 28rpx;
				color: #FFFFFF;
				text-align: center;
			}
		}

	}

	.popup-qr {
		display: flex;
		flex-direction: column;
		padding: 40rpx 30rpx;
		font-size: 28rpx;
		background-color: white;
		border-radius: 20rpx 20rpx 0 0;
		letter-spacing: 1px;
		box-sizing: border-box;
		align-items: center;
		position: relative;

		.title {
			font-weight: bold;
			font-size: 32rpx;
			color: #333333;
			margin-bottom: 20rpx;
			text-align: center;
		}

		.close {
			position: fixed;
			right: 0;
			top: 0;
			margin-top: 25rpx;
			margin-right: 25rpx;
		}

		.line {
			height: 1rpx;
			background-color: #E6E6E6;
			margin: 20rpx 0rpx;
			width: 100%;
		}



		.content {
			// border: 10rpx solid #24C78933;
			width: 70%;
			margin: 50rpx 0;
			text-align: center;
			background-color: #24C78933;

			image {
				width: 100%;
				background-color: white;
				border: 10rpx solid #24C78933;
				box-sizing: border-box;
			}

			.des {
				width: 100%;
				padding: 5rpx 0 15rpx 0rpx;
			}
		}

		.bottom-wrap {
			font-size: 30rpx;
			width: 100%;
			color: white;
			border-radius: 40rpx;
			padding: 20rpx 0rpx;
			background-color: #24C789;
			text-align: center;
			margin-bottom: 10rpx;
		}

	}
</style>